package com.wrupple.muba.catalogs.client.module.services.logic.impl;

import java.util.Collections;
import java.util.List;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wrupple.muba.catalogs.client.channels.CatalogDeletingChannel;
import com.wrupple.muba.catalogs.client.module.services.logic.EntryDeleteService;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.vegetate.domain.CatalogResponseContract;

public class EntryDeleteServiceImpl extends AbstractCatalogService implements EntryDeleteService {

	class DeleteCallback extends DataCallback<CatalogResponseContract>{
		StateTransition<CatalogEntry> callback;
		
		public DeleteCallback(StateTransition<CatalogEntry> callback) {
			super();
			this.callback = callback;
		}

		@Override
		public void execute() {
			List<CatalogEntry> response = (List<CatalogEntry>) result.getResponse();
			if(response!=null&&!response.isEmpty()){
				callback.setResultAndFinish(response.get(0));
			}
		}
		
	}
	

	private Provider<CatalogDeletingChannel> service;

	@Inject
	public EntryDeleteServiceImpl(Provider<CatalogDeletingChannel> service) {
		super();
		this.service = service;
	}


	@Override
	public void deleteEntry(String id, String catalogid, StateTransition<CatalogEntry> callback, EventBus eventBus) {
		callback.hook(new EntryDeleteServiceHook(catalogid,Collections.singletonList(id), eventBus));
		
		CatalogDeletingChannel served = service.get();
		catalogid = super.tokenizeCatalogId(catalogid, served);
		StateTransition<CatalogResponseContract> vegetateCallback = new DeleteCallback(callback);
		served.send(null, vegetateCallback, catalogid,"delete",id);
	}

}
